from PIL import Image
from StringIO import StringIO

# This function creates a PIL Image from raw image data.
def load_image_from_data(data):
    try:
        sio = StringIO(data)
        image = Image.open(sio)
    except Exception, e:
        raise Exception('Error loading image data, msg="%s"'%e.message)    
    return image
    
# This function extracts the raw image data from a PIL Image. 
def get_data_from_image(image, format = None):
    sio = StringIO()
    image.save(sio, format)
    return sio.getvalue()

def perform(image):
    # Load the image data into a PIL Image.
    pil_image = load_image_from_data(image)

    # Flip the image.
    flipped_image = pil_image.transpose(Image.FLIP_LEFT_RIGHT)
    
    # Return the image data.
    return get_data_from_image(flipped_image, pil_image.format)